package memory.net;

import java.io.IOException;
import java.net.*;

public class Multicast {
	
	private MulticastSocket socket;	  
	private InetAddress groupAddress;
	private int port;
	
	//Error messages;
	//private String failSend = "Couldn't send multicast packet";
	//private String failRecieve = "Couldn't recieve multicast packet";
	//private String failSocket  = "Can't create a multicast socket";
	
	public Multicast() throws IOException {

		createSocket("225.231.123.56", 9999);
		
	}
	
	public Multicast(String address, int port) throws IOException {
		createSocket(address, port);
	}
	
	private void createSocket(String address, int port) throws IOException {
		
		this.port = port;
						
		//Create socket
		socket = new MulticastSocket(port);
		socket.setSoTimeout(50);
		
		//Join the multicast group			
		groupAddress = InetAddress.getByName(address);
		socket.joinGroup(groupAddress);
		//System.out.println(socket.getLocalPort());
	
	}
	
	public void send(String s) throws IOException {
		//Create packet
		byte[] message = s.getBytes();		
		DatagramPacket packet = new DatagramPacket(message, message.length, groupAddress, port);
		
		//Send it.
		socket.send(packet);
	
	}
	
	public String recieve(int max_length) throws IOException {
		byte[] message = new byte[max_length];
		
		DatagramPacket packet = new DatagramPacket(message, message.length);
		
		try {
			socket.receive(packet);
		}
		catch (SocketTimeoutException e) {
			return null;
		}
		
		return new String(message, 0, packet.getLength());
	}
	
	public void closeSocket() {
		socket.close();
	}
	
	public MulticastSocket getSocket() {
		return socket;
	}

}
